<?php
/**
 * Created by PhpStorm.
 * User: hhcyc
 * Date: 2018/4/6
 * Time: 14:23
 */

namespace async;


class Mysql
{
    public $db = "";
    public $dbConfig = [];

    public function __construct()
    {
        // new \swoole_mysql;
        $this->db       = new \Swoole\Mysql;
        $this->dbConfig = [
            'host'     => '127.0.0.1',
            'port'     => 3306,
            'user'     => 'root',
            'password' => '36885158',
            'database' => 'swoole',
            'charset'  => 'utf8',
        ];
    }

    public function update()
    {

    }

    public function add()
    {

    }

    public function execute($id, $username)
    {
        $this->db->connect($this->dbConfig, function ($db, $result) use ($id, $username) {
            echo "mysql_connect" . PHP_EOL;

            if ($result === false) {
                var_dump($db->connect_error);
                return false;
            }


            //$sql = "select * from test where id=1";
            $sql = "update test set `username` = '{$username}' where `id`={$id}";


            // query （add select update delete）
            $db->query($sql, function ($db, $result) {
                // select => result 返回的是查询结果集
                // add update delete => result返回的是boole
                if ($result === false) {
                    var_dump($db->error);
                } elseif ($result === true) { // add update delete
                    var_dump($db->affected_rows);
                } else { // select
                    var_dump($result);
                }
                $db->close();
            });
        });
        return true;
    }
}

$mysql = new Mysql();
$flag  = $mysql->execute(1, 'hxs-1111');

var_dump($flag) . PHP_EOL;
echo "start" . PHP_EOL;